package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.apache.coyote.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import com.hmdp.utils.RedisConstants;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 *  服务实现类
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private HttpServletResponse httpServletResponse;

    /**
     * 查询缓存，添加缓存
     * @param id
     * @return
     */
    @Override
    public Result queryShopById(Long id) {
        Shop shop = queryWithPassThrough(id);//缓存空值 解决缓存穿透
        Shop shop1 = queryWithMutex(id);//互斥锁解决缓存击穿方案
        Shop shop2 = queryWithLogicalExpire(id);//逻辑过期解决缓存击穿方案
        return Result.ok(shop2);
    }

    /**
     * 缓存空值解决缓存穿透
     * @return
     */
    public Shop queryWithPassThrough(Long id){
//        1.根据id从redis中取商户
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);//ps：json格式的string反序列化为对象！！！
//        2.如果缓存命中，返回商户对象
        if (StrUtil.isNotBlank(shopJson)) { //isNotBlank只有有东西才为true（真命中）
            return JSONUtil.toBean(shopJson,Shop.class);
        }
        //一直不太懂这里返回null的逻辑是什么？为什么返回null
        if(shopJson==""){   //空命中
            return null;
        }
//        3.缓存未命中（shopJson为null)，走数据库
        Shop shop = getById(id);
//        4.数据库查不到，为了防止缓存击穿，先缓存一个null值再返回错误信息
        if (shop==null) {
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);//空值的ttl就设置个短一点的过期时间
            httpServletResponse.setStatus(404);
            return null;
        }
//        5.数据库查得到，写回redis;写缓存的时候添加ttl
        JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);//对象转回json字符串
//        6.返回商户
        return shop;
    }

    /**
     * 互斥锁解决缓存击穿
     * @param id
     * @return
     */
    private Shop queryWithMutex(Long id) {
//        1.根据id从redis中取商户
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);//ps：json格式的string反序列化为对象！！！
//        2.如果缓存命中，返回商户对象
        if (StrUtil.isNotBlank(shopJson)) { //isNotBlank只有有东西才为true（真命中）
            return JSONUtil.toBean(shopJson,Shop.class);
        }
        if(shopJson.equals("")){   //空命中
            return null;
        }
//        3.缓存未命中,尝试获取互斥锁
        String key=RedisConstants.LOCK_SHOP_KEY+id;
        Shop shop=null;
//        如果拿到了互斥锁
        if (tryLock(key)==true) {
//          再次检查redis缓存是否存在!!!
            try {
                String shopJson2 = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
                if (StrUtil.isNotBlank(shopJson2)) { //isNotBlank只有有东西才为true（真命中）
                    return JSONUtil.toBean(shopJson,Shop.class);
                }
                if(shopJson2.equals("")){   //空命中
                    return null;
                }
//          还是不存在就重建缓存
                shop = getById(id);
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//          数据库查不到，为了防止缓存击穿，先缓存一个null值再返回404
                if (shop==null) {
                    stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);//空值的ttl就设置个短一点的过期时间
                    httpServletResponse.setStatus(404);
                    return null;
                }
//          数据库查得到，写回redis;写缓存的时候添加ttl
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);//对象转回json字符串
//          6.返回商户
                return shop;
            } finally {
//          写完了就释放互斥锁
                unlock(key);
            }
        }else{
            //若没有获取到互斥锁
            try {
                Thread.sleep(10);
                String shopJson2 = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
                if (StrUtil.isNotBlank(shopJson2)) { //isNotBlank只有有东西才为true（真命中）
                    return JSONUtil.toBean(shopJson,Shop.class);
                }
                if(shopJson2.equals("")){   //空命中
                    return null;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        return shop;
    }

    /**
     * 获取锁(使用setnx模拟锁）
     * @param key
     * @return
     */
    public boolean tryLock(String key){
        //设置setnx
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        //返回值Boolean类型，避免拆箱报空指针异常使用工具类
        return BooleanUtil.isTrue(flag);//如果可以进行setnx则flag为true，返回true，否则返回false
    }

    /**
     * 释放锁
     * @param key
     */
    public void unlock(String key){
        //删除setnx设置的键
        stringRedisTemplate.delete(key);
    }

    /**
     * 逻辑过期解决缓存击穿
     */
    private static final ExecutorService CACHE_REBUILD_EXECUTORS=Executors.newFixedThreadPool(10);
    //这里不是用threadpoolexecutors创建线程池，是用Executors工具类创建
    public Shop queryWithLogicalExpire(Long id){
//        1.根据id从redis中取商户
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//        2.缓存未命中，直接返回null
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
//        3.缓存命中,先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject)redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
//        4.查看店铺对象是否逻辑过期
        if(redisData.getExpireTime().isAfter(LocalDateTime.now())){
            //尝试获取互斥锁
            try {
                boolean isLock = tryLock(LOCK_SHOP_KEY + id);
                if (isLock) {
                    //如果拿到互斥锁，先doublecheck看缓存是否过期
                    String shopJson2 = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
                    if (StrUtil.isBlank(shopJson2)) {
                        return null;
                    }
                    RedisData redisData2 = JSONUtil.toBean(shopJson2, RedisData.class);
                    JSONObject data2 = (JSONObject)redisData.getData();
                    Shop shop2 = JSONUtil.toBean(data2, Shop.class);
                    if(!(redisData2.getExpireTime().isAfter(LocalDateTime.now()))){//doublecheck缓存更新上来了，就不重建缓存了！！！
                        return shop2;
                    }
                    //doublecheck确定缓存是过期，开启一个新线程，重建缓存
                    CACHE_REBUILD_EXECUTORS.submit(()->saveShop2Redis(id,10L));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unlock(LOCK_SHOP_KEY+id);
            }
        }else {//未过期，直接返回商铺
            return shop;
        };
        //过期了返回过期的商铺，因为上面那个if语句里没写返回值
        return shop;
    }

    /**
     * 重建缓存
     */
    public void saveShop2Redis(Long id,Long expireTimes){
        //1.查询店铺数据
        Shop shop = getById(id);
        try {
            Thread.sleep(200);//模拟缓存重建的延迟
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //2.封装逻辑过期时间
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTimes));
        //3.店铺数据存入缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));//不设置TTL的！
    }

    /**
     * 更新缓存
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        if (shop.getId()==null) {
            return Result.fail("店铺id不能为空！");
        }
//        1.先更新数据库
        boolean b = updateById(shop);
//        2.删除redis缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
    /**
     * 分页查询店铺，同时查出店铺距离
     * @return
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
//        原来的分页查询实现
//        根据类型分页查询
//        Page<Shop> page = shopService.query()
//                .eq("type_id", typeId)
//                .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
//        返回数据
//        return Result.ok(page.getRecords());

        //1.判断是否需要根据坐标查询，如果前端没有传坐标，就还是原来的查询语句
        if (x == null || y == null) {
            //select x,y from tb_shop where type_id=#{};
            Page<Shop> page = query().eq("type_id", typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            //返回分页查询数据
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end=current * SystemConstants.DEFAULT_PAGE_SIZE;
        //3.查询redis、按照距离排序、分页；返回结果是shopId、distance
        String key=SHOP_GEO_KEY+typeId;
        //就是Geosearch，语句是GeoSearch key BYLONLAT x y BYRADIUS 5000 WITHDISTANCE
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key, GeoReference.fromCoordinate(x, y), new Distance(5000), RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));

        if(results==null){
            return Result.ok(Collections.emptyList());
        }
        //4.以下全部都是从results得到的list解析出id的部分
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        //截取from-end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> map = new HashMap<>(list.size());
        list.stream().skip(from).forEach(
                result->{
                    //获取店铺id
                    String id = result.getContent().getName();
                    ids.add(Long.valueOf(id));//引用类型String不能转引用类型Long吗？
                    //获取距离
                    Distance distance = result.getDistance();
                    map.put(id,distance);
                }
        );
        //根据id查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop:shops){
            shop.setDistance(map.get(shop.getId().toString()).getValue());//shop真有这个属性
        }
        return Result.ok(shops);


    }
}
